<?php
namespace app\web\controller;


class Tts extends Base
{
    public function Tts()
    {
//global $_G, $_P;
//$op = $_P['op'];
//$appkey = "uJwUlN4V4GqJj1H6";
//$accesskeyid = "LTAI5t7KX2RqZadVM1fsdhz8";
//$accessKeysecret = "jF0LjnniCCpg1cJP2F4hHXbuNmRHId";
////$token = "7a19fff842884136b4b5fa934592dbd8";
//if($op=='postTts'){
// //  $tts = self::processPOSTRequest($appkey,$accesskeyid,$accessKeysecret,$_P);
//
//   $tts = self::requestLongTts4Postself::processPOSTRequest($appkey,$accesskeyid,$accessKeysecret,$_P);
//
//    dump($tts);
//    return $tts;
//}elseif($op=='getZhubo'){
//    $zhubo =  self::getZhubo();
//    return $zhubo;
//}
//
//function getZhubo(){
//    $zhuboArray = [
//        ['name'=>'知米_多情感',   'code'=>'zhimi_emo',    'type'=>'多种情感女声'],
//        ['name'=>'知燕_多情感',   'code'=>'zhiyan_emo',   'type'=>'多种情感女声'],
//        ['name'=>'知贝_多情感',   'code'=>'zhibei_emo',   'type'=>'多种情感童声'],
//        ['name'=>'知甜_多情感',   'code'=>'zhitian_emo',  'type'=>'多种情感女声'],
//        ['name'=>'小云',         'code'=>'xiaoyun',      'type'=>'标准女声'],
//        ['name'=>'小刚',         'code'=>'xiaogang',     'type'=>'标准男声'],
//        ['name'=>'若兮',         'code'=>'ruoxi',        'type'=>'温柔女声'],
//        ['name'=>'思琪',         'code'=>'siqi',         'type'=>'温柔女声'],
//        ['name'=>'思佳',         'code'=>'sijia',        'type'=>'标准女声'],
//        ['name'=>'思诚',         'code'=>'sicheng',      'type'=>'标准男声'],
//        ['name'=>'艾琪',         'code'=>'aiqi',         'type'=>'温柔女声'],
//        ['name'=>'艾佳',         'code'=>'aijia',        'type'=>'标准女声'],
//        ['name'=>'艾诚',         'code'=>'aicheng',      'type'=>'标准男声'],
//        ['name'=>'艾达',         'code'=>'aida',         'type'=>'标准男声'],
//        ['name'=>'宁儿',         'code'=>'ninger',       'type'=>'标准女声'],
//        ['name'=>'瑞琳',         'code'=>'ruilin',       'type'=>'标准女声'],
//        ['name'=>'思悦',         'code'=>'siyue',        'type'=>'温柔女声'],
//        ['name'=>'艾雅',         'code'=>'aiya',         'type'=>'严厉女声'],
//        ['name'=>'艾夏',         'code'=>'aixia',        'type'=>'亲和女声'],
//        ['name'=>'艾美',         'code'=>'aimei',        'type'=>'甜美女声'],
//        ['name'=>'艾雨',         'code'=>'aiyu',         'type'=>'自然女声'],
//        ['name'=>'艾悦',         'code'=>'aiyue',        'type'=>'温柔女声'],
//        ['name'=>'艾婧',         'code'=>'aijing',       'type'=>'严厉女声'],
//        ['name'=>'小美',         'code'=>'xiaomei',      'type'=>'甜美女声'],
//        ['name'=>'艾娜',         'code'=>'aina',         'type'=>'浙普女声'],
//        ['name'=>'伊娜',         'code'=>'yina',         'type'=>'浙普女声'],
//        ['name'=>'思婧',         'code'=>'sijing',       'type'=>'严厉女声'],
//        ['name'=>'思彤',         'code'=>'sitong',       'type'=>'儿童音'],
//        ['name'=>'小北',         'code'=>'xiaobei',      'type'=>'萝莉女声'],
//        ['name'=>'艾彤',         'code'=>'aitong',       'type'=>'儿童音'],
//        ['name'=>'艾薇',         'code'=>'aiwei',        'type'=>'萝莉女声'],
//        ['name'=>'艾宝',         'code'=>'aibao',        'type'=>'萝莉女声'],
//        ['name'=>'姗姗',         'code'=>'shanshan',     'type'=>'粤语女声'],
//        ['name'=>'艾媛',         'code'=>'aiyuan',       'type'=>'知心姐姐'],
//        ['name'=>'艾颖',         'code'=>'aiying',       'type'=>'软萌童声'],
//        ['name'=>'艾祥',         'code'=>'aixiang',      'type'=>'磁性男声'],
//        ['name'=>'艾墨',         'code'=>'aimo',         'type'=>'情感男声'],
//        ['name'=>'艾晔',         'code'=>'aiye',         'type'=>'青年男声'],
//        ['name'=>'艾婷',         'code'=>'aiting',       'type'=>'电台女声'],
//        ['name'=>'艾凡',         'code'=>'aifan',        'type'=>'情感女声'],
//        ['name'=>'小玥',         'code'=>'chuangirl',    'type'=>'四川话女声'],
//        ['name'=>'艾硕',         'code'=>'aishuo',       'type'=>'自然男声'],
//        ['name'=>'艾德',         'code'=>'aide',         'type'=>'新闻男声'],
//        ['name'=>'青青',         'code'=>'qingqing',     'type'=>'中国台湾话女声'],
//        ['name'=>'翠姐',         'code'=>'cuijie',       'type'=>'东北话女声'],
//        ['name'=>'小泽',         'code'=>'xiaoze',       'type'=>'湖南重口音男声'],
//        ['name'=>'艾楠',         'code'=>'ainan',        'type'=>'广告男声'],
//        ['name'=>'艾浩',         'code'=>'aihao',        'type'=>'资讯男声'],
//        ['name'=>'艾茗',         'code'=>'aiming',       'type'=>'诙谐男声'],
//        ['name'=>'艾笑',         'code'=>'aixiao',       'type'=>'资讯女声'],
//        ['name'=>'艾厨',         'code'=>'aichu',        'type'=>'舌尖男声'],
//        ['name'=>'艾倩',         'code'=>'aiqian',       'type'=>'资讯女声'],
//        ['name'=>'艾树',         'code'=>'aishu',        'type'=>'资讯男声'],
//        ['name'=>'艾茹',         'code'=>'airu',         'type'=>'新闻女声'],
//        ['name'=>'佳佳',         'code'=>'jiajia',       'type'=>'粤语女声'],
//        ['name'=>'桃子',         'code'=>'taozi',        'type'=>'粤语女声'],
//        ['name'=>'柜姐',         'code'=>'guijie',       'type'=>'亲切女声'],
//        ['name'=>'马树',         'code'=>'mashu',        'type'=>'儿童剧男声'],
//        ['name'=>'知琪',         'code'=>'zhiqi',        'type'=>'温柔女声'],
//        ['name'=>'知厨',         'code'=>'zhichu',       'type'=>'舌尖男声'],
//        ['name'=>'小仙',         'code'=>'xiaoxian',     'type'=>'亲切女声'],
//        ['name'=>'悦儿',         'code'=>'yuer',         'type'=>'儿童剧女声'],
//        ['name'=>'猫小美',       'code'=>'maoxiaomei',   'type'=>'活力女声'],
//        ['name'=>'知祥',         'code'=>'zhixiang',     'type'=>'磁性男声'],
//        ['name'=>'知佳',         'code'=>'zhijia',       'type'=>'标准女声'],
//        ['name'=>'知楠',         'code'=>'zhinan',       'type'=>'广告男声'],
//        ['name'=>'知倩',         'code'=>'zhiqian',      'type'=>'资讯女声'],
//        ['name'=>'知茹',         'code'=>'zhiru',        'type'=>'新闻女声'],
//        ['name'=>'知德',         'code'=>'zhide',        'type'=>'新闻男声'],
//        ['name'=>'知飞',         'code'=>'zhifei',       'type'=>'激昂解说'],
//        ['name'=>'艾飞',         'code'=>'aifei',        'type'=>'激昂解说'],
//        ['name'=>'亚群',         'code'=>'yaqun',        'type'=>'卖场广播'],
//        ['name'=>'巧薇',         'code'=>'qiaowei',      'type'=>'卖场广播'],
//        ['name'=>'大虎',         'code'=>'dahu',         'type'=>'东北话男声'],
//        ['name'=>'知伦',         'code'=>'zhilun',       'type'=>'悬疑解说'],
//        ['name'=>'艾伦',         'code'=>'ailun',        'type'=>'悬疑解说'],
//        ['name'=>'杰力豆',       'code'=>'jielidou',     'type'=>'治愈童声'],
//        ['name'=>'知薇',         'code'=>'zhiwei',       'type'=>'萝莉女声'],
//        ['name'=>'老铁',         'code'=>'laotie',       'type'=>'东北老铁'],
//        ['name'=>'老妹',         'code'=>'laomei',       'type'=>'吆喝女声'],
//        ['name'=>'艾侃',         'code'=>'aikan',        'type'=>'天津话男声'],
//        ['name'=>'知甜',         'code'=>'zhitian',      'type'=>'甜美女声'],
//        ['name'=>'知青',         'code'=>'zhiqing',      'type'=>'中国台湾话女生']
//    ];
//     return_json(0,'',$zhuboArray);
//}
//
//function getAliToken($accesskeyid,$accessKeysecret){
//    date_default_timezone_set("Etc/GMT");
//    $one = md5(time());
//    $parms = array(
//        "AccessKeyId" => $accesskeyid,
//        "Action" => "CreateToken",
//        "Version" => "2019-02-28",
//        "Format" => "JSON",
//        "RegionId" => "cn-shanghai",
//        "Timestamp" => date("Y-m-d\TH:i:s\Z"),
//        "SignatureMethod" => "HMAC-SHA1",
//        "SignatureVersion" => "1.0",
//        "SignatureNonce" => substr($one,0,8)."-".substr($one,8,4)."-".substr($one,12,4)."-".substr($one,16,4)."-".substr($one,20,4),
//    );
//    ksort($parms);
//    $query = http_build_query($parms);
//    $stringToSign = "GET&%2F&" . urlencode($query);
//    $signature = urlencode(base64_encode(hash_hmac("sha1",$stringToSign,$accessKeysecret."&",true)));
//    $queryStringWithSign = "Signature=". $signature ."&". $query;
//    $tokenUrl = "http://nls-meta.cn-shanghai.aliyuncs.com/?".$queryStringWithSign;
//    $token_string = self::urlOpen($tokenUrl);
//    $token_object = json_decode($token_string,true);
//    $token = $token_object['Token']['Id'];
//    return $token;
//}
//
//function urlOpen($url,$data = null,$header =null){
//    $ch =curl_init();
//    curl_setopt($ch,CURLOPT_URL,$url);
//    //curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
//    //curl_setopt($ch,CURLOPT_USERAGENT,$url,$ua);
//    if($data){
//        curl_setopt($ch,CURLOPT_POST,1);
//        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
//    }
//    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//    curl_setopt($ch,CURLOPT_REFERER,$url);
//    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
//    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
//    $content = curl_exec($ch);
//    $error = curl_error($ch);
//    if($error){
//        die($error);
//    }
//    curl_close($ch);
//    return $content;
//}
//
//// 长文本语音合成restful接口，支持post调用，不支持get请求。发出请求后，可以轮询状态或者等待服务端合成后自动回调（如果设置了回调参数）。
//function requestLongTts4Postself::processPOSTRequest($appkey,$accesskeyid,$accessKeysecret,$_P)  {
//    $token = self::getAliToken($accesskeyid,$accessKeysecret);
//    $volume = $_P['sound_slide'];
//    //语速
//    $speech_rate =  $_P['yusu_slide'];
//    //语调
//    $pitch_rate =  $_P['yudiao_slide'];
//
//    $text = $_P['text'];
//
//    $format = "wav";
//    $voice = "xiaogang";
//    $sampleRate = 16000;
//
//    $url = "https://nls-gateway.cn-shanghai.aliyuncs.com/rest/v1/tts/async";
//
//    // 拼接HTTP Post请求的消息体内容。
//    $header = array("appkey" => $appkey, "token" => $token);
//    $context = array("device_id" => "my_device_id");
//    $tts_request = array("text" => $text, "format" => $format, "voice" => $voice, "sample_rate" => $sampleRate, "enable_subtitle" => false);
//    $payload = array("enable_notify" => true, "notify_url" => "http://123.com", "tts_request" => $tts_request);
//    $tts_body = array("context" => $context, "header" => $header, "payload" => $payload);
//    $body = json_encode($tts_body);
//   // print "The POST request body content: " . $body . "\n";
//    $httpHeaders = array("Content-Type: application/json");
//    $curl = curl_init();
//    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
//    curl_setopt($curl, CURLOPT_URL, $url);
//    curl_setopt($curl, CURLOPT_POST, TRUE);
//    curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
//    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($curl, CURLOPT_HEADER, TRUE);
//    $response = curl_exec($curl);
//    if ($response == FALSE) {
//        print "curl_exec failed!\n";
//        curl_close($curl);
//        return ;
//    }
//    $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
//    $headers = substr($response, 0, $headerSize);
//    $bodyContent = substr($response, $headerSize);
//    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//    dump($http_code);
//    if($http_code != 200) {
//        print "tts request failure, error code = " . $http_code . "\n";
//        print "tts request failure, response = " . $bodyContent . "\n";
//        return ;
//    }
//    curl_close($curl);
//    $data = json_decode($bodyContent, true);
//    if( isset($data["error_code"]) && $data["error_code"] == 20000000) {
//        $task_id = $data["data"]["task_id"];
//        $request_id = $data["request_id"];
//        print "Request Success! task_id = " . $task_id . "\n";
//        print "Request Success! request_id = " . $request_id . "\n";
//        ///说明：轮询检查服务端的合成状态，轮询操作非必须，如果设置了回调url，则服务端会在合成完成后主动回调。
//        self::waitLoop4Complete($url, $appkey, $token, $task_id, $request_id);
//    } else {
//        print "Request Error: status=" . $data["status"] . "; error_code=" . $data["error_code"] . "; error_message=" . $data["error_message"] . "\n";
//    }
//}
//
//
//function waitLoop4Complete($url, $appkey, $token, $task_id, $request_id) {
//    $fullUrl = $url . "?appkey=" . $appkey . "&task_id=" . $task_id . "&token=" . $token . "&request_id=" . $request_id;
//    print "query url = " . $fullUrl . "\n";
//    while(true) {
//        $curl = curl_init();
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
//        curl_setopt($curl, CURLOPT_URL, $fullUrl);
//        curl_setopt($curl, CURLOPT_HEADER, TRUE);
//        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
//        $response = curl_exec($curl);
//        if ($response == FALSE) {
//            print "curl_exec failed!\n";
//            curl_close($curl);
//            return ;
//        }
//        // 处理服务端返回的响应。
//        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
//        $headers = substr($response, 0, $headerSize);
//        $bodyContent = substr($response, $headerSize);
//        print $bodyContent."\n";
//        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//        if($http_code != 200) {     // 如果请求失败，需要检查调用是否正确。
//            print "tts request failure, error code = " . $http_code . "\n";
//            curl_close($curl);
//            return ;
//        }
//        curl_close($curl);
//        $data = json_decode($bodyContent, true);
//
//        //$data["data"]["audio_address"]== null时表示还在合成未完成的状态,需要等待。。。
//        if(isset($data["error_code"]) && $data["error_code"] == 20000000
//            && isset($data["data"]) && $data["data"]["audio_address"]== null){
//
//            print "Tts Queuing...please wait..." . "\n";
//
//        }
//        else if(isset($data["error_code"]) && $data["error_code"] == 20000000
//            && isset($data["data"]) && $data["data"]["audio_address"] != "")  {
//            print "Tts Finished! task_id = " . $data["data"]["task_id"] . "\n";
//            print "Tts Finished! audio_address = " . $data["data"]["audio_address"] . "\n";
//            break;
//        }
//        // 每隔10秒钟轮询一次状态。
//        sleep(10);
//    }
//}
//
//function processPOSTRequest($appkey,$accesskeyid,$accessKeysecret,$_P) {
//    //$url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts";
//    $url = "nls-gateway-cn-shanghai.aliyuncs.com/ws/v1";
//    $text = $_P['text'];
//    $textUrlEncode = urlencode($text);
//    $textUrlEncode = preg_replace('/\+/', '%20', $textUrlEncode);
//    $textUrlEncode = preg_replace('/\*/', '%2A', $textUrlEncode);
//    $textUrlEncode = preg_replace('/%7E/', '~', $textUrlEncode);
//    $voice = $_P['zhubo'];
//    //音量
//    $volume = $_P['sound_slide'];
//    //语速
//    $speech_rate =  $_P['yusu_slide'];
//    //语调
//    $pitch_rate =  $_P['yudiao_slide'];
//    /**请求参数，以JSON格式字符串填入HTTPS POST请求的Body中。*/
//    $token = self::getAliToken($accesskeyid,$accessKeysecret);
//
//    $format = "mp3";
//    $sampleRate = 16000;
//    $taskArr = array(
//        "appkey" => $appkey,
//        "token" => $token,
//        "text" => $textUrlEncode,
//        "format" => $format,
//        "sample_rate" => $sampleRate,
//        // voice 发音人，可选，默认是xiaoyun。
//        "voice" => $voice,
//        // volume 音量，范围是0~100，可选，默认50。
//        "volume" => $volume,
//        // speech_rate 语速，范围是-500~500，可选，默认是0。
//        "speech_rate" => $speech_rate,
//        // pitch_rate 语调，范围是-500~500，可选，默认是0。
//        "pitch_rate" => $pitch_rate
//    );
//
//    $body = json_encode($taskArr);
//    $curl = curl_init();
//    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
//    /*设置HTTPS POST URL。*/
//    curl_setopt($curl, CURLOPT_URL, $url);
//    curl_setopt($curl, CURLOPT_POST, TRUE);
//    /*设置HTTPS POST请求头部。*/
//    $httpHeaders = array(
//        "Content-Type: application/json"
//    );
//    curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
//    /*设置HTTPS POST请求体。*/
//    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
//    /*设置返回的响应包含HTTPS头部信息。*/
//    curl_setopt($curl, CURLOPT_HEADER, TRUE);
//    /*发送HTTPS POST请求。 */
//    $response = curl_exec($curl);
//
//    if ($response == FALSE) {
//        curl_close($curl);
//        return_json(1,"curl_exec failed!");
//        return ;
//    }
//    /*处理服务端返回的响应。*/
//    $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
//    $headers = substr($response, 0, $headerSize);
//    $bodyContent = substr($response, $headerSize);
//    if (stripos($headers, "Content-Type: audio/mpeg") != FALSE || stripos($headers, "Content-Type:audio/mpeg") != FALSE) {
//       // $res = file_put_contents('audioFile/'.$audioSaveFile, $bodyContent);
//        $base64String = 'data:' . 'audio/mpeg' . ';base64,' . chunk_split(base64_encode($bodyContent));
//        return $base64String;
//    }
//    else {
//        print "The POST request failed: " . $bodyContent . "\n";
//    }
//}
global $_G, $_P;
$apiKey = "ct5VFZSubee88r3WmS7TpAKF";
$secretKey = "QNuKPGUdKkIsKBo0BrUnXOUNB7io7Lt3";
const ADD_BGM_URL= 'https://audio.yixuan.net/tts.php';
$op = $_P['op'];
$module_name = MODULE_NAME;
if($op=='postTts'){
     //判断次数
    $text = $_P['text'];
    //主播
    $voice = $_P['zhubo'];
     //判断是否有更改
    $volume = $_P['sound_slide'];
    //语速
    $speech =  $_P['yusu_slide'];
    //语调
    $pitch=  $_P['yudiao_slide'];

    $themeid = $_P['themeid'];

    $sql = " select * from ".tablename(t_tts)." where softname='{$module_name}' and themeid={$themeid} and config->'$.voice'='{$voice}' and config->'$.volume'='{$volume}' and config->'$.speech'='{$speech}' and config->'$.pitch'='{$pitch}' and text = '{$text}'";

    $tts_info = db_find($sql);
    $bgm_src = $_P['bgm_src'];
    if(!strstr($bgm_src,"http")){
        $bgm_src = "http://img2020.yixuansoft.cn/".$bgm_src;
    }

    $return_time = strtotime($tts_info['return_time']);
    $id = 0;
    if($tts_info){
        $id = $tts_info['id'];
    }

    if($tts_info&&time()-$return_time<72*3600){      //存在判断背景音乐
        //背景音乐地址
        $old_bgm_src = '';
        $config =  json_decode($tts_info['config'],true);
        if(isset($config['bgm_src'])){
            $old_bgm_src = $config['bgm_src'];
        }

        if($old_bgm_src==$bgm_src&&$tts_info['audio_url']){
            return_json(0,'',['audio_url'=>$tts_info['audio_url'],'id' => $tts_info['id']]);
        }else{   //背景合成
            $speech_url = $tts_info['speech_url'];
            $add_bgm_url = ADD_BGM_URL;
            $add_bgm_array = [
                'audio_url'  => $speech_url,
                'bgm_url' => $bgm_src,
                'act_code' => MODULE_NAME
            ];
            $res =  self::curl($add_bgm_url,$add_bgm_array);
            $res_array = json_decode($res,true);
            if($res_array['code']==1){
                $audio_url = $res_array['data']['audio_url'];
                $update_data['audio_url'] = $audio_url;
                $now_time = date('Y-m-d H:i:s',time());
                $update_field= "  audio_url = '{$audio_url}',config=JSON_SET(config,'$.\"bgm_src\"','$bgm_src'),update_time = '{$now_time}'";
                $update_sql = "UPDATE ".tablename(t_tts)." SET ".$update_field .' where id ='.$tts_info['id'];
                $res = db_query($update_sql);
                return_json(0,'',['audio_url'=>$audio_url,'id'=>$tts_info['id']]);
            }else{
                return_json(1,$res_array['msg']);
            }
        }
    }else{
        $tts = self::baiduTts($apiKey,$secretKey,$_P,$id);
        return $tts;
    }

}elseif($op == 'getTts'){
    $id = $_P['id'];
    $tts_info = self::getTts($apiKey,$secretKey,$id);
    return $tts_info;
}elseif($op == 'getBgm'){
    $id = $_P['id'];
    $bgm_info = self::getBgm($id);
    return $bgm_info;
}elseif($op=='getZhubo'){
    $zhubo =  self::getZhubo();
    return $zhubo;
}elseif ($op=='lastTts'){
    $tts_url = self::lastTts($_P);
    return $tts_url;
}elseif ($op == 'entryTts'){
    $audio_url = $_P['audio_url'];
    $id = $_P['id'];
    $oss = self::oss($audio_url);
    if($oss['code']==1){
         return_json($oss['code'],$oss['msg']);
    }
    $audio_url = $oss['data']['audio_url'];
    $update_data['audio_url'] = $audio_url;
    $update_data['status'] = 4;
    $update_data['update_time'] = date('Y-m-d H:i:s',time());
    //上传oss
    db_update(t_tts,$update_data,array("id"=>$id));
    return_json($oss['code'],'',$oss['data']);
}

function getZhubo(){
    $zhuboArray = [
        ['name'=>'小美',   'code'=>0,   'type'=>'成熟女声'],
        ['name'=>'小宇',   'code'=>1,   'type'=>'成熟男声'],
        ['name'=>'小逍遥', 'code'=>3,   'type'=>'磁性男声'],
        ['name'=>'丫丫',   'code'=>4,   'type'=>'可爱女声'],

        ['name'=>'小鹿',   'code'=>5118,   'type'=>'甜美女声'],
        ['name'=>'小娇',   'code'=>5,   'type'=>'情感女声'],
        ['name'=>'大逍遥',  'code'=>5003,  'type'=>'磁性男声'],
        ['name'=>'博文',   'code'=>106,   'type'=>'情感男声'],
        ['name'=>'米朵',   'code'=>103,   'type'=>'可爱女童'],
        ['name'=>'小童',   'code'=>110,   'type'=>'活泼女童'],
        ['name'=>'小萌',   'code'=>111,   'type'=>'可爱女童'],
    ];
    return_json(0,'',$zhuboArray);
}

function getBaiduToken($apiKey,$secretKey)
{
    $auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" . $apiKey . "&client_secret=" . $secretKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $auth_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名,0不验证
    $res = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    curl_close($ch);
    // echo "Token URL response is " . $res . "\n";
    $response = json_decode($res, true);
    if (!isset($response['access_token'])) {
        echo "ERROR TO OBTAIN TOKEN\n";
        exit(1);
    }
    if (!isset($response['scope'])) {
        echo "ERROR TO OBTAIN scopes\n";
        exit(2);
    }

    if (!in_array('audio_tts_post', explode(" ", $response['scope']))) {
        echo "DO NOT have tts permission\n";
        // 请至网页上应用内开通语音合成权限
        exit(3);
    }

    $token = $response['access_token'];
    $cache_baidu_token = 'baidu_'.$apiKey;
    cache_write($cache_baidu_token,[
        'access_token' => $token,
        'expires_in' => time() + $response['expires_in'] ,
    ]);
    return $token;
}

function baiduTts($apiKey,$secretKey,$_P,$id=0){
    //获取token
     if(cache_load('baidu_'.$apiKey)){
         $baidu_token = cache_load('baidu_'.$apiKey);
         $expires_in = $baidu_token['expires_in'];
         if($expires_in-time()>120){
            $token =  $baidu_token['access_token'];
         }else{
             $token = self::getBaiduToken($apiKey,$secretKey);
         }
     }else{
         $token = self::getBaiduToken($apiKey,$secretKey);
     }

     $text = $_P['text'];
     if(empty($text)){
           return_json(1,'请输入要转换的文本');
     }

//     $textUrlEncode = urlencode($text);
//     $textUrlEncode = preg_replace('/\+/', '%20', $textUrlEncode);
//     $textUrlEncode = preg_replace('/\*/', '%2A', $textUrlEncode);
//     $textUrlEncode = preg_replace('/%7E/', '~', $textUrlEncode);
     $themeid = $_P['themeid'];

     $voice = $_P['zhubo'];
     //音量
     $volume = $_P['sound_slide'];
     //语速
     $speech =  $_P['yusu_slide'];
     //语调
     $pitch=  $_P['yudiao_slide'];
     //背景音乐地址
     $bgm_src = $_P['bgm_src'];
     //背景音乐音量
     $params = array(
        'text' => $text,
        'voice' => $voice,
        'volume' =>intval($volume),
        'speech' =>intval($speech),
        'pitch' =>intval($pitch),
        'format' => 'mp3-16k',
        'lang' => 'zh', //固定参数
     );

     $data = json_encode($params);
     $url = "https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=".$token;
     $curl = curl_init();
     curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>$data,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),
     ));
    //添加数据
     $response = curl_exec($curl);
     curl_close($curl);
    $response_array = json_decode($response,true);
     if($id>0){    //编辑
         $update_data['config'] = json_encode([
             'format' => 'mp3-16k',
             'voice' => $voice,
             'pitch' => $pitch,
             'speech' => $speech,
             'volume' => $volume,
             'bgm_src' => $bgm_src
         ]);
         $update_data['return'] = $response;
         $update_data['update_time'] = date('Y-m-d H:i:s',time());
         if(isset($response_array['task_id'])){
             $status= 1;
             //获取语音播报
             $update_data['task_ids'] = $response_array['task_id'];
         }else{
             $msg = $response_array['error_code'].':'.$response_array['error_msg'];
             $status = -1;
         }

         if(db_update(t_tts,$update_data,array("id"=>$id))){
         //    self::getTts($apiKey,$secretKey,$tts_data,$id,$bgm_src,$themeid);
             $res_data['id'] = $id;
             //调用合成语音合成
             if($status==1&&empty($msg)){
                 return_json(0,'',$res_data);
             }else{
                 return_json(1,$msg,$res_data);
             }
         }else{
             return_json(1,'添加数据失败');
         }
     }else{  //添加
         $insert_data['softname']  = MODULE_NAME;
         $insert_data['themeid']  = $themeid;
         $insert_data['text'] = $text;
         $insert_data['config'] = json_encode([
             'format' => 'mp3-16k',
             'voice' => $voice,
             'pitch' => $pitch,
             'speech' => $speech,
             'volume' => $volume,
             'bgm_src' => $bgm_src
         ]);

         $insert_data['api'] = 'baidu';
         $insert_data['return'] = $response;
         $insert_data['create_time'] = date('Y-m-d H:i:s',time());
         $msg = '';
         if(isset($response_array['task_id'])){
             $status= 1;
             //获取语音播报
             $insert_data['task_ids'] = $response_array['task_id'];
         }else{
             $msg = $response_array['error_code'].':'.$response_array['error_msg'];
             $status = -1;
         }
         $insert_data['status'] = $status;
         if($insertid = db_insert(t_tts,$insert_data)){
             $tts_id =  $insertid;
             $res_data['id'] = $tts_id;
             //调用合成语音合成
             if($status==1&&empty($msg)){
                 return_json(0,'语音合成成功',$res_data);
             }else{
                 return_json(1,$msg,$res_data);
             }
         }else{
             return_json(1,'添加数据失败');
         }
    }
}
//播放
function lastTts($_P){
    $module_name = MODULE_NAME;
    $themeid = $_P['themeid'];
    $sql = " select id,config,text,audio_url  from ".tablename(t_tts)." where   softname='{$module_name}' and themeid = {$themeid} order by id desc";
    $tts_info = db_find($sql);
    if($tts_info){
         return_json(0,'',$tts_info);
    }
}
//获取语音播报
function getTts($apiKey,$secretKey,$id){
     $sql = " select id,task_ids,status  from ".tablename(t_tts)." where id = {$id}";
     $tts_info = db_find($sql);
     if(!$tts_info){
         return_json(1,'数据不存在');
     }

     if($tts_info['status']!=1){
         return_json(1,'状态不正确');
     }

     if(!$tts_info['task_ids']){
         return_json(1,'缺少参数');
     }

     $tts_data['task_ids'] = [$tts_info['task_ids']];
    //获取token
    if(cache_load('baidu_'.$apiKey)){
        $baidu_token = cache_load('baidu_'.$apiKey);
        $expires_in = $baidu_token['expires_in'];
        if($expires_in-time()>3600){
            $token =  $baidu_token['access_token'];
        }else{
            $token = self::getBaiduToken($apiKey,$secretKey);
        }
    }else{
        $token = self::getBaiduToken($apiKey,$secretKey);
    }

    $tts_data = json_encode($tts_data);
    $url = "https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=" . $token;
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $tts_data,
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Accept: application/json'
        ),
    ));
    $update_data['update_time'] = date('Y-m-d H:i:s',time());
    $tts_response = curl_exec($curl);
    curl_close($curl);
    $tss_query_array = json_decode($tts_response, true);
    $update_data['return_time'] = date('Y-m-d H:i:s',time());
    $update_data['query_return'] = $tts_response;
    if(isset($tss_query_array['error_code'])){   //存在错误
            $update_data['status'] = -2;
            db_update(t_tts,$update_data,array("id"=>$id));
            return_json(1,$tss_query_array['error_code']);
    }else{
        if($tss_query_array['tasks_info'][0]['task_status']=='Success'){             //出现错误
            $update_data['status'] = 2;
            $speech_url = $tss_query_array['tasks_info'][0]['task_result']['speech_url'];
            $update_data['speech_url'] = $speech_url;
            db_update(t_tts,$update_data,array("id"=>$id));
            $res_data['id'] = $id;
            return_json(0,'',$res_data);
        }elseif ($tss_query_array['tasks_info'][0]['task_status']=='Failure'){      //合成失败
            $update_data['status'] = -2;
            db_update(t_tts,$update_data,array("id"=>$id));
            return_json(1,'合成失败');
        }
    }
}

function getBgm($id){
    $sql = " select id,config,speech_url,status  from ".tablename(t_tts)." where id = {$id}";
    $tts_info = db_find($sql);
    $speech_url = $tts_info['speech_url'];
    $config =  json_decode($tts_info['config'],true);
    $bgm_url = $config['bgm_src'];

    $add_bgm_url = ADD_BGM_URL;
    $add_bgm_array = [
        'audio_url'  => $speech_url,
        'bgm_url' => $bgm_url,
        'act_code' => MODULE_NAME
    ];
    $res =  self::curl($add_bgm_url,$add_bgm_array);
    $audio_res = json_decode($res,true);
    if($audio_res['code']==1) {
        $audio_url = $audio_res['data']['audio_url'];
        $update_data['audio_url'] = $audio_url;
    }else{
        return_json(1,'',$audio_res['msg']);
    }
    $update_data['status'] = 3;
    $update_data['update_time'] = date('Y-m-d H:i:s',time());
    db_update(t_tts,$update_data,array("id"=>$id));
    $res_data['audio_url'] = $audio_url;
    $res_data['id'] = $id;
    return_json(0,'',$res_data);
}

function curl($url, $post = false,$header = [])
{
    $headerArray = array_merge($header, [
        'Expect:',
    ]);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if ($post) {
        curl_setopt($ch, CURLOPT_TIMEOUT,60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function oss($audio_url){
     $root_path = IA_ROOT."/attachment/";
     $out_path = 'audios/'.date('Y-m').'/'.MODULE_NAME.'/';
     if (!is_dir($root_path.$out_path)) {
        mkdirs($root_path.$out_path);
     }
     $scene = MODULE_NAME;
     $file_name = md5(json_encode($audio_url.$scene.TIMESTAMP)).'.mp3';
     $audio_path = $root_path.$out_path.$file_name;
     file_put_contents($audio_path,file_get_contents($audio_url));
     $postaudio =  $out_path .$file_name ;
     $remotestatus = file_remote_upload($postaudio); //上传图片到远程
     if (is_error($remotestatus)) {
         return ['code'=>1,'msg'=>'语音生成失败'];
        exit;
     } else {
        $ossurl = tomedia($postaudio);  // 远程图片的访问URL
        $data = ['audio_url'=>$ossurl];
        return ['code' =>0,'msg'=>'','data' => $data];
     }
}


}
}